import { observer } from 'mobx-react'
import styles from './index.module.less'
import store from '../../store'
import { useRef, useState } from 'react'
import { Image, ImageViewer, Toast } from 'antd-mobile'
import RainbowChart from '@/components/RainbowChart'

const Rainbow = () => {
    const { fileDetail } = store || {}
    const chartRef = useRef<any>()
    const [img, setImg] = useState<string>()
    const [visible, setVisible] = useState(false)

    /** 图片预览 */
    const previewImage = (event: React.MouseEvent<HTMLImageElement, Event>) => {
        event.stopPropagation()
        ImageViewer.show({ image: fileDetail.rainbow_url?.url })
    }

    const handlePreview = async () => {
        if (!img) {
            Toast.show('正在生成预览...')
            const url: string = await chartRef?.current?.exportImg()
            setImg(url)
            Toast.clear()
        }
        setVisible(true)
    }

    return (
        <div className={styles.container}>
            <div className={styles.form_wrapper}>
                <div className={styles.title}>
                    <span className={styles.title_span}>我的生涯彩虹图</span>
                </div>
                {fileDetail?.detail?.length && (
                    <div>
                        <div className={styles.rainbow_container} onClick={handlePreview}>
                            {fileDetail.rainbow_url?.url ? (
                                <Image className={styles.image} src={fileDetail.rainbow_url?.url} onClick={previewImage} />
                            ) : (
                                <RainbowChart data={fileDetail?.detail} ref={chartRef} width={(343 / 375) * window.innerWidth} />
                            )}
                        </div>
                        {fileDetail?.detail?.map((item: any, index: number) => {
                            return (
                                <div className={styles.block_title} key={item?.id || index}>
                                    <span>
                                        角色{index + 1}：{item?.name}
                                    </span>
                                    <span>
                                        时间广度：{item?.age_start}岁~
                                        {item?.age_end}岁
                                    </span>
                                </div>
                            )
                        })}
                    </div>
                )}
            </div>

            <ImageViewer
                image={img}
                visible={visible}
                onClose={() => {
                    setVisible(false)
                }}
            />
        </div>
    )
}

export default observer(Rainbow)
